
package com.ciei.dpagm.util;


import com.sun.mail.util.MailSSLSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.security.GeneralSecurityException;
import java.util.List;
import java.util.Properties;



/**
 * @author kiho
 * @date 2019/12/30 19:22
 **/


@Component
public class EmailUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(EmailUtil.class);

    @Value("${mail.mailFrom}")
    private String mailFrom;// 发件人
    @Value("${mail.password}")
    private String password_mailFrom;// 发件人邮箱的授权码
    @Value("${mail.host}")
    private String mail_host; // 发件人的服务器域名
    @Value("${mail.port}")
    private String port ;                   //端口


/**
     * 发送邮件
     * @param contactEmails 收件人地址
     * @param subject 邮件的主题
     * @param content   邮件的正文内容
     * @param attachPath    附件文件路径
     * @return
     * @author kiho
     * @date 2019/12/30 0030
     */
    public void send(List<String> contactEmails, String subject, String content, List<String> attachPath){
        Properties prop = new Properties();
        //服务器
        prop.setProperty("mail.host", mail_host);
        //协议
        prop.setProperty("mail.transport.protocol", "smtp");
        //端口
        prop.setProperty("mail.smtp.port", port);
        //使用smtp身份验证
        prop.setProperty("mail.smtp.auth", "true");
        //开启安全协议
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
        } catch (GeneralSecurityException e1) {
            e1.printStackTrace();
        }
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);
        try {
            // 使用JavaMail发送邮件的5个步骤
            // 1、创建session
            Session session = Session.getInstance(prop);
            // 开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
//        session.setDebug(true);
            // 2、通过session得到transport对象
            Transport ts = session.getTransport();
            // 3、连上邮件服务器，需要发件人提供邮箱的用户名和密码进行验证
            ts.connect(mail_host, mailFrom, password_mailFrom);// 需要修改
            // 4、创建邮件
            MimeMessage message = new MimeMessage(session);
            // 设置邮件的基本信息
            message.setFrom(new InternetAddress(mailFrom));	// 发件人
            InternetAddress[] sendTo = new InternetAddress[contactEmails.size()];
            for (int i = 0; i < contactEmails.size(); i++) {
                sendTo[i] = new InternetAddress(contactEmails.get(i));
            }
            message.setRecipients(Message.RecipientType.TO,sendTo);// 多个收件人
            message.setSubject(subject);// 邮件主题

            // 创建容器描述数据关系
            MimeMultipart mp = new MimeMultipart();

            // 创建邮件正文，为了避免邮件正文中文乱码问题，需要使用charset=UTF-8指明字符编码
            MimeBodyPart text = new MimeBodyPart();
            text.setContent(content, "text/html;charset=UTF-8");
            mp.addBodyPart(text);

            // 设置附件
            if (attachPath != null && attachPath.size() > 0) {
                for (int i = 0; i < attachPath.size(); i++) {
                    MimeBodyPart attach = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(attachPath.get(i));
                    DataHandler dh = new DataHandler(fds);
                    attach.setDataHandler(dh);
//                    attach.setFileName(dh.getName());
                    attach.setFileName(MimeUtility.encodeText(fds.getName(), "UTF-8", "B"));
                    mp.addBodyPart(attach);
                }
            }

            mp.setSubType("mixed");

            message.setContent(mp);
            message.saveChanges();
            // 将创建的Email写入到F盘存储
//            message.writeTo(new FileOutputStream("D:\\wkh\\文档资料\\耐久台\\mail\\ImageMail.eml"));// 需要修改
            // 5、发送邮件
            ts.sendMessage(message, message.getAllRecipients());
            ts.close();
            LOGGER.info("邮件发送给："+contactEmails.toString());
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}



